package com.example.medicalapp.activity;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.medicalapp.R;
import com.example.medicalapp.helper.DatabaseHelper;
import com.example.medicalapp.util.PreferencesUtil;
import com.google.android.material.textfield.TextInputLayout;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Pattern;

public class AppointmentActivity extends AppCompatActivity {
    private static final String TAG = "AppointmentActivity";
    private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm";
    private static final int INTERVAL_MINUTES = 15; // 预约间隔15分钟
    // 姓名验证正则表达式（支持汉字、字母和少数特殊字符）
    private static final String NAME_PATTERN = "^[\\u4E00-\\u9FA5a-zA-Z·]{2,20}$";

    private TextView tvDeptInfo;
    private EditText etName;
    private EditText etIdCard;
    private Button btnSubmit;
    // 添加TextInputLayout引用用于错误提示
    private TextInputLayout tilName;
    private TextInputLayout tilIdCard;

    private int deptId;
    private String deptName;
    private DatabaseHelper dbHelper;
    private PreferencesUtil preferencesUtil;
    private Pattern namePattern;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_appointment);
        Log.d(TAG, "onCreate called");

        // 初始化正则表达式
        namePattern = Pattern.compile(NAME_PATTERN);

        // 初始化视图
        initViews();

        // 初始化数据库和偏好设置工具
        dbHelper = new DatabaseHelper(this);
        preferencesUtil = new PreferencesUtil(this);

        // 获取从上一个页面传递的科室信息
        getIntentData();

        // 添加输入框焦点变化监听器，清除错误提示
        setupFocusListeners();
    }

    private void initViews() {
        tvDeptInfo = findViewById(R.id.tv_dept_info);
        tilName = findViewById(R.id.til_name);
        tilIdCard = findViewById(R.id.til_id_card);
        etName = findViewById(R.id.et_name);
        etIdCard = findViewById(R.id.et_id_card);
        btnSubmit = findViewById(R.id.btn_submit);

        // 设置挂号按钮点击事件
        btnSubmit.setOnClickListener(v -> submitAppointment());
    }

    /**
     * 设置输入框焦点监听器，当获取焦点时清除错误提示
     */
    private void setupFocusListeners() {
        etName.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                tilName.setError(null);
                tilName.setErrorEnabled(false);
            }
        });

        etIdCard.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                tilIdCard.setError(null);
                tilIdCard.setErrorEnabled(false);
            }
        });
    }

    private void getIntentData() {
        // 获取科室ID和名称
        deptId = getIntent().getIntExtra(PatientHomeActivity.EXTRA_DEPT_ID, -1);
        deptName = getIntent().getStringExtra(PatientHomeActivity.EXTRA_DEPT_NAME);

        if (deptId == -1 || deptName == null) {
            Log.e(TAG, "Invalid department data received");
            finish();
            return;
        }

        // 显示科室信息
        tvDeptInfo.setText("科室：" + deptName);
        Log.d(TAG, "Received department: " + deptName + " (ID: " + deptId + ")");
    }

    private void submitAppointment() {
        // 清除之前的错误提示
        tilName.setError(null);
        tilIdCard.setError(null);
        tilName.setErrorEnabled(false);
        tilIdCard.setErrorEnabled(false);

        // 获取输入信息
        String patientName = etName.getText().toString().trim();
        String idCard = etIdCard.getText().toString().trim();

        // 验证输入
        if (!validateName(patientName)) {
            return;
        }

        if (!validateIdCard(idCard)) {
            return;
        }

        // 获取当前登录患者ID
        int patientId = preferencesUtil.getUserId();
        if (patientId == -1) {
            Log.e(TAG, "Cannot get patient ID from SharedPreferences");
            Toast.makeText(this, "登录状态异常，请重新登录", Toast.LENGTH_SHORT).show();
            return;
        }

        // 计算预约时间
        String appointmentTime = calculateAppointmentTime();
        if (appointmentTime == null) {
            Toast.makeText(this, "计算预约时间失败", Toast.LENGTH_SHORT).show();
            return;
        }

        // 插入预约记录到数据库
        long result = dbHelper.insertAppointment(
                patientId,
                deptId,
                patientName,
                idCard,
                appointmentTime,
                "pending" // 初始状态为待诊
        );

        if (result != -1) {
            Log.d(TAG, "Appointment created successfully with ID: " + result);
            showSuccessDialog(appointmentTime);
        } else {
            Log.e(TAG, "Failed to create appointment");
            Toast.makeText(this, "挂号失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 验证姓名输入
     */
    private boolean validateName(String name) {
        if (name.isEmpty()) {
            tilName.setErrorEnabled(true);
            tilName.setError("请输入您的姓名");
            etName.requestFocus();
            return false;
        }

        if (!namePattern.matcher(name).matches()) {
            tilName.setErrorEnabled(true);
            tilName.setError("请输入有效的姓名（2-20个字符）");
            etName.requestFocus();
            return false;
        }

        return true;
    }

    /**
     * 验证身份证号输入
     */
    private boolean validateIdCard(String idCard) {
        if (idCard.isEmpty()) {
            tilIdCard.setErrorEnabled(true);
            tilIdCard.setError("请输入身份证号");
            etIdCard.requestFocus();
            return false;
        }

        if (idCard.length() != 18) {
            tilIdCard.setErrorEnabled(true);
            tilIdCard.setError("请输入18位有效身份证号");
            etIdCard.requestFocus();
            return false;
        }

        // 可以添加更复杂的身份证号验证规则
        return true;
    }

    /**
     * 计算新的预约时间
     * @return 格式化的时间字符串
     */
    private String calculateAppointmentTime() {
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, Locale.getDefault());
        Calendar calendar = Calendar.getInstance();

        // 查询该科室最近的预约时间
        String lastTime = dbHelper.getLatestAppointmentTime(deptId);
        Log.d(TAG, "Latest appointment time for dept " + deptId + ": " + lastTime);

        try {
            if (lastTime == null) {
                // 没有预约记录，从今天09:00开始
                calendar.set(Calendar.HOUR_OF_DAY, 9);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
            } else {
                // 有最近记录，在其基础上加15分钟
                Date lastDate = sdf.parse(lastTime);
                calendar.setTime(lastDate);
                calendar.add(Calendar.MINUTE, INTERVAL_MINUTES);
            }

            // 格式化时间并返回
            return sdf.format(calendar.getTime());
        } catch (ParseException e) {
            Log.e(TAG, "Error parsing date: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 显示挂号成功对话框
     */
    private void showSuccessDialog(String appointmentTime) {
        new AlertDialog.Builder(this)
                .setTitle("挂号成功")
                .setMessage("您已成功预约" + deptName + "\n" +
                        "就诊时间：" + appointmentTime + "\n" +
                        "请提前15分钟到达候诊")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 返回患者主页
                        finish();
                    }
                })
                .setCancelable(false)
                .show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbHelper != null) {
            dbHelper.close();
        }
        Log.d(TAG, "onDestroy called");
    }
}